package com.penglecode.netty.client;

import java.util.Properties;

import org.apache.commons.pool.impl.GenericObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.penglecode.netty.NettyException;
import com.penglecode.netty.pool.PoolableNettyClientFactory;

public class NettyProxyFactory {

	private static final Logger logger = LoggerFactory.getLogger(NettyProxyFactory.class);
	
	private GenericObjectPool<NettyClient> nettyClientPool;
	
	private String serverHost;
	
	private Properties poolConfigProperties;
	
	private int port;
	
	public NettyProxyFactory(String serverHost, int port) {
		super();
		this.serverHost = serverHost;
		this.port = port;
		initPool();
	}
	
	protected void initPool(){
		GenericObjectPool.Config poolConfig = new GenericObjectPool.Config();
		if(poolConfigProperties != null){
			poolConfig = null; //@todo
		}
		this.nettyClientPool = new GenericObjectPool<NettyClient>(new PoolableNettyClientFactory(this.serverHost, this.port), poolConfig);
	}

	public <T> T createProxy(Class<T> serviceClass){
		NettyClient nettyClient = null;
		try {
			nettyClient = nettyClientPool.borrowObject();
			return nettyClient.createProxy(serviceClass);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new NettyException(e.getMessage(), e);
		} finally {
			if(nettyClient != null){
				try {
					nettyClientPool.returnObject(nettyClient);
				} catch (Exception e) {
					logger.error(e.getMessage(), e);
					throw new NettyException(e.getMessage(), e);
				}
			}
		}
	}
	
}
